package com.umb.cs.class1.impl;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;



import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.xpath.XPathExpression;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.sun.org.apache.xerces.internal.parsers.DOMParser;
import com.umb.cs.class1.api.BookVO;

 class ParseURL {
	
	private static List<String> authorNames = new ArrayList<String>();
	private static String formatedAuthorName=null;
	private static String formatedArticleTitle=null;
	private static String formatedJournalName=null;
	private static String vol;
	private static String iss;
	private static int year; 
	private static int sp; 
	private static String crossrefDOI;
	private static String doiURL;
	static HttpURLConnection conn = null;
	List<BookVO> b;
	
	 
		
	public static String formateString(String s){
		String formatedString=s;
		Boolean found=false;
		 Pattern pattern = Pattern.compile("\\(.+?\\)");
			
		 Matcher matcher = pattern.matcher(formatedString);
		 
		if(found = matcher.find()){
			System.out.println("Found"+found);
			formatedString = formatedString.replaceAll("\\(.+?\\)","").trim();
		}
		formatedString=formatedString.replaceAll(" ", "%20").trim();
		return formatedString;
	}
//	public static String mergeTitle(List<String> str){
//		String s1 = "";
//
//		for (String str1 : str)
//		{
//		    s1 += " "+str1.trim();
//		}
//		return s1;
//		
//	}
	public static String aURLBuilder(BookVO b){
			
    	StringBuilder builder= null;
    	 	
    	 builder = new StringBuilder();
    	 builder.append("http://crossref.org/openurl?pid=sadhanareddy.p@gmail.com") ;

    		
    		String s3=b.getTitle();
    		formatedArticleTitle=formateString(s3).trim();
    		builder.append("&stitile="+formatedArticleTitle);
    		
    		if(b.getAuthor().get(0) != null){
    		authorNames=b.getAuthor();
    		formatedAuthorName=formateString(authorNames.get(0).trim());
    		builder.append("&aulast="+formatedAuthorName);
    		}
    		
    		if(b.getVolume() != null){
    			
		    		vol=b.getVolume().trim();
		    		builder.append("&volume="+vol);
    			
    		}
    		if(b.getIssue()!= null){
    		iss=b.getIssue().trim();
    		builder.append("&issue="+iss);
    		}
    		if(b.getYear()!= null){
    			try{
		    		year=Integer.parseInt(b.getYear().trim());
		    		builder.append("&date="+year);
    			}catch(java.lang.NumberFormatException e){
    				
    			}
    		}
    		if(b.getPage()!= null){
    			try{
    		sp=Integer.parseInt(b.getPage().trim());
    		builder.append("&spage="+sp);
    			}catch(java.lang.NumberFormatException e){}
    		}
    		if(b.getJournal()!= null){
    		formatedJournalName=formateString(b.getJournal().trim());
    		builder.append("&title="+formatedJournalName);
    		}
    		builder.append("&noredirect=true");
    		//URL aURL = new URL("http://crossref.org/openurl?pid=sadhanareddy.p@gmail.com&stitle="+formatedArticleTitle+"&aulast="+formatedAuthorName+"&title=AM%20MIDL%20NAT"+"&volume="+vol+"&spage="+sp+"&date="+year+"&noredirect=true");
    		
    		System.out.println("URL="+builder.toString());
		return builder.toString(); 
	}
	
	public static List<BookVO> fetchDOI() throws IOException, SAXException{
		
  		int count=0;
		 int j=0;
		File file = new File("C:\\Users\\sadhanapalugulla\\Desktop\\Classes\\write.txt");
	    Writer output = null;
	    output = new BufferedWriter(new FileWriter(file));
		ParserManager m = new ParserManager();
		List<BookVO> blist = m.parseMetadata();	
		URL aURL = null;
		for(BookVO b: blist){
	   		count++;
	   		if(count%300>=1)
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					
					e.printStackTrace();
				}
	   		aURL = new URL(aURLBuilder(b));
	   	  		
	   		conn = (HttpURLConnection) aURL.openConnection();
																
				if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
					System.out.println( "Connection established" );
					  DOMParser parser = new DOMParser();
				      InputStream in = conn.getInputStream();
				      InputSource source = new InputSource(in);
				      parser.parse(source);
				      in.close();
				      conn.disconnect();
				      Document doc = parser.getDocument();
				     
				      NodeList nodeLst=doc.getElementsByTagName("body");
				     
				      for(int index=0; index < nodeLst.getLength(); index++)
				      {
				              Node node = nodeLst.item(index);
				       
					      	if (node.getNodeType() == Node.ELEMENT_NODE)
					      	{
					      	        Element element = (Element) node;
					      	     NodeList nameNode=element.getElementsByTagName("query");
				      				Element query = (Element) nameNode.item(0);
				      				String status=query.getAttributeNode("status").getValue().trim().toString();
				      				
					      	        if(status.equalsIgnoreCase("resolved")){
					      	        		
					      	        	 	nameNode = element.getElementsByTagName("doi");
								      		Element DOI = (Element) nameNode.item(0);
								      		if(DOI!=null){
								      			crossrefDOI=DOI.getFirstChild().getTextContent();
								      			b.setDoi(crossrefDOI);
								      			doiURL="http://dx.doi.org/"+crossrefDOI.trim();
								      			b.setDoiURL(doiURL);
							      			System.out.println(b.getDoiURL());
							      				System.out.println("DOI = " +DOI.getFirstChild().getTextContent());
		//						      			System.out.println(DOI.getNodeName());
							      				
								      		}
						      				
						      				nameNode=element.getElementsByTagName("volume");
						      				Element volume = (Element) nameNode.item(0);
						      				if(volume!=null){
						      					b.setVolume(volume.getFirstChild().getTextContent());
						      				}
						      				nameNode=element.getElementsByTagName("issue");
						      				Element issue = (Element) nameNode.item(0);
						      				if(issue!=null){
						      					b.setIssue(issue.getFirstChild().getTextContent());
						      				}
						      				
						      				nameNode=element.getElementsByTagName("journal_title");
						      				Element journalT = (Element) nameNode.item(0);
						      				if(journalT!=null){
						      					b.setJournal(journalT.getFirstChild().getTextContent());
	
						      				}
						      				nameNode=element.getElementsByTagName("first_page");
						      				Element frstPage = (Element) nameNode.item(0);
						      				if(frstPage!=null){
						      					b.setPage(frstPage.getFirstChild().getTextContent());
						      				}
						      				
						      				nameNode=element.getElementsByTagName("issn");
						      				Element issn = (Element) nameNode.item(0);
						      				if(issn!=null){
						      					b.setIssn(issn.getFirstChild().getTextContent());
		
						      				}
						      				
						      				nameNode=element.getElementsByTagName("article_title");
						      				Element artTitle = (Element) nameNode.item(0);
						      				if(artTitle!=null){
						      					b.setArticleTitle(artTitle.getFirstChild().getTextContent());
	
						      				}
						      				
						      				nameNode=element.getElementsByTagName("year");
						      				Element year = (Element) nameNode.item(0);
						      				if(year!=null){
						      					b.setYear(year.getFirstChild().getTextContent());
						      				}
						      				System.out.println(j);
						      				j++;
						      				
					      	        }else{}
			    						      				
					          }
				      }
				}
				output.close();
				System.out.println("Connection Closed");
	
		}
		System.out.println("List returned");
		return blist;
	}
	
	    public static void main(String[] args) throws Exception {
	    	List<BookVO> book= fetchDOI();
	    	
	    	if(book!=null){
	    		for(BookVO bk: book){
	    			System.out.println("Main:"+bk.getDoi());
	    			
	    		}
	    	}
	    }
	    	  
 }  

